package com.sun.aspect;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * log切面
 * 
 * @author sun
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    /** 用来记录请求进入的时间，防止多线程时出错，这里用了ThreadLocal */
    private static final ThreadLocal<Long> START_TIME = new NamedThreadLocal<>("StopWatch-StartTime");

    public static Object get() {
        return START_TIME.get();
    }

    public static void set(Long time) {
        START_TIME.set(time);
    }

    public static void clear() {
        START_TIME.remove();
    }

    /** 定义切入点 */
    @Pointcut("@annotation(com.sun.aspect.WebLog)")
    public void webLog() {
    }

    /**
     * 方法之前执行，日志打印请求信息
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                    .currentRequestAttributes();
            HttpServletRequest request = attributes.getRequest();

            // 设置请求开始时间
            START_TIME.set(System.currentTimeMillis());
            // 打印请求 url
            log.info("URL            : {}", request.getRequestURL().toString());
            // 打印描述信息
            log.info("Description    : {}", getAspectLogDescription(joinPoint));
            // 打印 Http method
            log.info("HTTP Method    : {}", request.getMethod());
            // 打印请求的 IP
            log.info("IP             : {}", request.getRemoteAddr());
            // 打印请求入参
            log.info("Request Args   : {}", new Gson().toJson(joinPoint.getArgs()[0]));
        } catch (Exception e) {
            log.error("Exception", e);
            // 回收ThreadLocal变量
            LogAspect.clear();
        }
    }

    /**
     * 方法返回之前执行，打印才返回值以及方法消耗时间
     */
    @AfterReturning(returning = "response", pointcut = "webLog()")
    public void doAfterRunning(Object response) throws Throwable {
        // 打印返回值信息
        log.info("Response            : {}", response != null ? new Gson().toJson(response) : "");

        // 打印请求耗时
        log.info("Request spend times : {}ms", System.currentTimeMillis() - START_TIME.get());
    }

    /**
     * 获取切面注解的描述
     */
    @SuppressWarnings("rawtypes")
    public String getAspectLogDescription(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        StringBuilder description = new StringBuilder();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description.append(method.getAnnotation(WebLog.class).value());
                    break;
                }
            }
        }
        return description.toString();
    }

}
